package com.qd.panda.service.park;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.panda.domain.entity.carpark.CarParkGasStationNozzleDTO;
import com.qd.panda.mapper.park.CarParkGasStationNozzleMapper;
import com.qd.panda.model.CarParkGasStationNozzle;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;

/**
 * 油枪号信息
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class CarParkGasStationNozzleService extends BaseService<CarParkGasStationNozzleMapper, CarParkGasStationNozzle> {

    private static final String PREFIX_ID = "panda_car_park_gas_station_nozzle_id_{0}";
    private static final String PREFIX_LIST = "panda_car_park_gas_station_nozzle_pId_{0}";
    private static final String PREFIX_UNIQUE_PANDA_CAR = "panda_car_park_gas_station_nozzle_pId_{0}_nozzleNumber_{1}_octaneNumber_{2}";

    private final RedisTemplateUtil<CarParkGasStationNozzle> redisTemplateUtil;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public CarParkGasStationNozzleDTO save(CarParkGasStationNozzleDTO dto) {
        checkUnique(dto);
        final CarParkGasStationNozzle model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public CarParkGasStationNozzleDTO update(CarParkGasStationNozzleDTO dto) {
        checkUnique(dto);
        final CarParkGasStationNozzle historyModel = Optional.ofNullable(getById(dto.getId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final CarParkGasStationNozzle model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            clearCache(model);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<CarParkGasStationNozzle> mList) {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchIds(List<CarParkGasStationNozzle> mList) {
        final List<String> ids = mList.stream().map(CarParkGasStationNozzle::getId).collect(toList());
        final List<CarParkGasStationNozzle> historyModelList = checkIds(ids);
        try {
            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param id 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String id) {
        final CarParkGasStationNozzle historyModel = Optional.ofNullable(getById(id)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(id)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        final List<CarParkGasStationNozzle> historyModelList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(CarParkGasStationNozzleDTO dto) {
        final QueryWrapper<CarParkGasStationNozzle> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param id 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String id) {
        boolean exists = false;
        if (StringUtils.hasLength(id)) {
            final CarParkGasStationNozzle model = getById(id);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param id 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public CarParkGasStationNozzle getById(String id) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, id);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(id), CarParkGasStationNozzle.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param id 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public CarParkGasStationNozzleDTO getByIdDto(String id) {
        return Optional.ofNullable(getById(id)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public CarParkGasStationNozzle getOne(CarParkGasStationNozzleDTO dto) {
        final QueryWrapper<CarParkGasStationNozzle> queryWrapper = createQueryWrapper(dto);
        CarParkGasStationNozzle model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public CarParkGasStationNozzleDTO getOneDto(CarParkGasStationNozzleDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<CarParkGasStationNozzle> getList(CarParkGasStationNozzleDTO dto) {
        final QueryWrapper<CarParkGasStationNozzle> queryWrapper = createQueryWrapper(dto);
        final List<CarParkGasStationNozzle> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<CarParkGasStationNozzleDTO> getListDto(CarParkGasStationNozzleDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 根据唯一性索引获得数据
     * param pId 停车场ID
     * param nozzleNumber 枪号
     * param octaneNumber 油耗
     *
     * @return 单条数据
     */
    @Transactional(readOnly = true)
    public CarParkGasStationNozzle getUniqueByPIdAndNozzleNumber(String pId, String nozzleNumber, Integer octaneNumber) {
        final QueryWrapper<CarParkGasStationNozzle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("p_id", pId);
        queryWrapper.eq("nozzle_number", nozzleNumber);
        queryWrapper.eq("octane_number", octaneNumber);
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_CAR, pId, nozzleNumber, octaneNumber);
        final CarParkGasStationNozzle model = redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getOne(queryWrapper, false), CarParkGasStationNozzle.class);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据枪号获得油号
     * param pId 停车场ID
     * param nozzleNumber 枪号
     *
     * @return 单条数据
     */
    @Transactional(readOnly = true)
    public Integer getOctaneNumberByPIdAndNozzleNumber(String pId, String nozzleNumber) {
        final QueryWrapper<CarParkGasStationNozzle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("p_id", pId);
        queryWrapper.eq("nozzle_number", nozzleNumber);
        CarParkGasStationNozzle carParkGasStationNozzle = super.getOne(queryWrapper, false);
        queryWrapper.clear();
        return Optional.ofNullable(carParkGasStationNozzle).map(CarParkGasStationNozzle::getOctaneNumber).orElse(-1);
    }

    /**
     * 验证唯一性索引
     *
     * @param dto 页面对象
     */
    private void checkUnique(CarParkGasStationNozzleDTO dto) {
        CarParkGasStationNozzle model = getUniqueByPIdAndNozzleNumber(dto.getPId(), dto.getNozzleNumber(), dto.getOctaneNumber());
        if (null != model) {
            checkUnique(dto, model);
        }
    }

    /**
     * 验证唯一性索引
     *
     * @param dto   页面对象
     * @param model 根据约束字段查询出来的数据库对象
     */
    private void checkUnique(CarParkGasStationNozzleDTO dto, CarParkGasStationNozzle model) {
        if (!StringUtils.hasLength(dto.getId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
        if (!dto.getId().equals(model.getId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(CarParkGasStationNozzle model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getId()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST, model.getPId()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_CAR, model.getPId(), model.getNozzleNumber(), model.getOctaneNumber()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<CarParkGasStationNozzle> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getId())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
        List<String> uniqueIds = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_CAR, model.getPId(), model.getNozzleNumber(), model.getOctaneNumber())).collect(toList());
        if (!uniqueIds.isEmpty()) {
            redisTemplateUtil.deleteByKey(uniqueIds);
            uniqueIds.clear();
        }
        Set<String> parkIds = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST, model.getPId())).collect(toSet());
        if (!parkIds.isEmpty()) {
            redisTemplateUtil.deleteByKey(parkIds);
            parkIds.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public CarParkGasStationNozzleDTO modelToDto(CarParkGasStationNozzle model) {
        if (null == model) {
            return null;
        }
        final CarParkGasStationNozzleDTO dto = new CarParkGasStationNozzleDTO();
        dto.setId(model.getId());
        dto.setOctaneNumber(model.getOctaneNumber());
        dto.setNozzleNumber(model.getNozzleNumber());
        dto.setPId(model.getPId());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public CarParkGasStationNozzle dtoToModel(CarParkGasStationNozzleDTO dto) {
        if (null == dto) {
            return null;
        }
        final CarParkGasStationNozzle model = new CarParkGasStationNozzle();
        model.setId(dto.getId());
        model.setOctaneNumber(dto.getOctaneNumber());
        model.setNozzleNumber(dto.getNozzleNumber());
        model.setPId(dto.getPId());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(CarParkGasStationNozzleDTO dto) {

    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<CarParkGasStationNozzleDTO> modelToDtoList(List<CarParkGasStationNozzle> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<CarParkGasStationNozzle> dtoToModelList(List<CarParkGasStationNozzleDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<CarParkGasStationNozzle> createQueryWrapper(CarParkGasStationNozzleDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<CarParkGasStationNozzle> createQueryWrapper(CarParkGasStationNozzleDTO dto, String tableAlias) {
        final QueryWrapper<CarParkGasStationNozzle> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getNozzleNumber())) {
                queryWrapper.eq(tableAlias + "nozzle_number", dto.getNozzleNumber());
            }
            if (StringUtils.hasLength(dto.getPId())) {
                queryWrapper.eq(tableAlias + "p_id", dto.getPId());
            }
        }
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<CarParkGasStationNozzle> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<CarParkGasStationNozzle> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(CarParkGasStationNozzle::getId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteCarParkGasStationNozzleByParkId(String parkId) {
        QueryWrapper<CarParkGasStationNozzle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("p_id", parkId);
        final List<CarParkGasStationNozzle> carParkGasStationNozzles = getBaseMapper().selectList(queryWrapper);
        queryWrapper.clear();
        if(!carParkGasStationNozzles.isEmpty()){
            final List<String> ids = carParkGasStationNozzles.stream().map(CarParkGasStationNozzle::getId).collect(toList());
            removeBatchIds(ids);
            ids.clear();
        }
    }

    @Transactional(readOnly = true)
    public List<CarParkGasStationNozzle> getGasStationNozzleListByParkId(String parkId) {
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST, parkId);
        return redisTemplateUtil.getList(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> {
            QueryWrapper<CarParkGasStationNozzle> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("p_id", parkId);
            queryWrapper.orderByAsc("nozzle_number");
            final List<CarParkGasStationNozzle> carParkGasStationPrices = getBaseMapper().selectList(queryWrapper);
            queryWrapper.clear();
            return carParkGasStationPrices;
        }, CarParkGasStationNozzle.class);
    }

    @Transactional(readOnly = true)
    public List<CarParkGasStationNozzleDTO> getGasStationNozzleDtoListByParkId(String parkId) {
        return Optional.ofNullable(getGasStationNozzleListByParkId(parkId)).map(this::modelToDtoList).orElse(Collections.emptyList());
    }
}